<!--
 * @Project_description: 角色添加编辑
-->
<template>
  <div class='role-add'>
    <el-dialog v-drag :before-close='handleClose' :title='title' :visible.sync='dialogVisible' width='33%'>
      <el-form ref='form' :disabled='loading' :model='form' :rules='rules' label-width='100px'>
        <el-form-item label='角色名称' prop='roleName'>
          <el-input v-model='form.roleName' clearable minlength='10' placeholder='请输入角色名称'></el-input>
        </el-form-item>
        <el-form-item label='角色编号' prop='roleCode'>
          <el-input v-model='form.roleCode' clearable minlength='10' placeholder='请输入角色编号'></el-input>
        </el-form-item>
        <el-row>
          <el-col :span='12'>
            <el-form-item label='状态' prop='state'>
              <el-radio-group v-model='form.state'>
                <el-radio :label='0'>启用</el-radio>
                <el-radio :label='1'>禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='显示排序' prop='sortKey'>
              <el-input-number v-model='form.sortKey' :min='0' controls-position='right' />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label='菜单权限'>
          <el-checkbox v-model='menuExpand' @change='treeExpand($event)'>展开/折叠</el-checkbox>
          <el-checkbox v-model='menuNodeAll' @change='treeNodeAll($event)'>全选/全不选</el-checkbox>
          <el-checkbox v-model='menuCheckStrictly' @change='treeConnect($event)'>父子联动</el-checkbox>
          <el-tree
            ref='menu'
            :check-strictly='!menuCheckStrictly'
            :data='menuOptions'
            :default-checked-keys='userMenu'
            :props='defaultProps'
            class='tree-border'
            empty-text='加载中，请稍候'
            node-key='permissionId'
            show-checkbox
          ></el-tree>
        </el-form-item>
        <el-form-item label='备注' prop='intro'>
          <el-input v-model='form.intro' :rows='3' maxlength='150'
                    placeholder='请输入备注' type='textarea' />
        </el-form-item>
      </el-form>
      <!-- 下放按钮 -->
      <span slot='footer' class='dialog-footer'>
        <el-button :loading='loading' type='primary' @click='onSuccess'>保 存</el-button>
        <el-button @click='dialogVisible = false'>取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import handleMenuData from '@/views/sys/role/components/handleMenuData'
import validator from '@/libs/utli.validator'

export default {
  name: 'role-add',
  data() {
    // 这里存放数据
    return {
      dialogVisible: false,
      loading: false,
      title: '添加',
      form: {
        'roleName': '',
        'roleCode': '',
        'intro': '',
        state: 0,
        orgId: '',
      },
      //默认
      defaultProps: {
        children: 'children',
        label: 'permissionName',
      },
      isPut: false,
      rules: {
        'roleName': [
          {
            'required': true,
            'message': '角色名称不能为空',
            'trigger': 'blur',
          },
        ],
        'roleCode': [
          {
            'required': true,
            'message': '角色编号不能为空',
            'trigger': 'blur',
          },
          {
            'validator': validator.chinese,
            'trigger': 'blur',
          },
        ],
      },
      //展开折叠
      menuExpand: false,
      //全部
      menuNodeAll: false,
      //父子联动
      menuCheckStrictly: true,
      // 菜单列表
      menuOptions: [],
      //默认选中
      userMenu: [],
    }
  },
  // 方法集合
  methods: {
    //初始化
    init(row) {
      let _this = this
      if (row) {
        this.isPut = true
        this.title = '编辑'
        this.form = row
      } else {
        this.isPut = false
        this.form = {
          orgId: this.$db._getUser('currentOrgId'),
          'roleName': '',
          'roleCode': '',
          'intro': '',
          state: 0,
          sortKey: 0,
        }
      }
      //展开折叠
      this.menuExpand = false
      //全部
      this.menuNodeAll = false
      //父子联动
      this.menuCheckStrictly = true
      //打开dlog
      this.dialogVisible = true
      //获取权限tree
      this.getTree()
      //移除表单校验结果
      setTimeout(() => {
        _this.$refs.form.clearValidate()
        _this._getRules(_this.$refs.form)
      })
    },
    // 关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {
        })
    },

    //树权限（展开/折叠）
    treeExpand(value) {
      let treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].permissionId].expanded = value
      }
    },
    //获取权限树
    async getTree() {
      let res = await this.$api.menu.tree()
      this.menuOptions = res.data
      //好球麻烦的
      this.setMenuKeys(res.data)
    },
    //设置树节点选中
    setMenuKeys(tree) {
      //用户的树节点
      let userMenu = this.deepClone(this.form.permissionList.map(i => i.permissionId))
      const newRoleMenu = handleMenuData(tree, userMenu)
      this.userMenu = newRoleMenu
    },
    //全选
    treeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
    },
    //父子联动
    treeConnect(value) {
      this.menuCheckStrictly = value ? true : false
    },
    // 所有菜单节点数据
    getMenuAllKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },

    //提交
    async onSuccess() {
      let _this = this
      _this.$refs.form.validate(async (valid) => {
        if (valid) {
          _this.loading = true
          _this.form.permissionList = _this.getMenuAllKeys()
          try {
            if (_this.isPut) {
              // 修改
              await _this.$api.role.put(_this.form)
              _this.$message.success('修改成功')
            } else {
              // 添加
              await _this.$api.role.add(_this.form)
              _this.$message.success('添加成功')
            }
            await _this.$emit('load')
            _this.dialogVisible = false
            _this.loading = false
          } catch (error) {
            _this.loading = false

          }
        } else {
          console.log('validate error')
        }
      })
    },
  },
}
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #FFFFFF none;
  border-radius: 4px;
}
</style>
